// pages/conformOrder/index.js
const api = require('../../utils/request')
const utils = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: undefined,
    cart:{},
    count: 0,
    total:0,
    totalFormat:'',
    extText: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // const self = this;
    // wx.getStorage({
    //   key: 'cart',
    //   success (res) {
    //     const count = res.data.cartData.reduce((total , cur)=>{
    //       return total + cur.count
    //     },0)
    //     let total = utils.formatPrice(res.data.total)
    //     self.setData({
    //       cart: res.data,
    //       count,
    //       total
    //     })
    // }})
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    try {
      var value = wx.getStorageSync('addressid')
      if (value) {
        this.getPrepareOrder(value);
      }else{
        this.getPrepareOrder();
      }
    } catch (e) {
      // Do something when catch error
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  gotoAddress(){
    wx.navigateTo({
      url: '/pages/address/index',
    })
  },
  submitOrder(){
    console.log('submit')
  },// ee0a24
  getPrepareOrder(id){
    let data={}
    if(id){
      data['chosenAddressId']=id
    }
    api.get('/user/order/prepareCheckout',data).then(res=>{
      
      let total=0,count=0;
      res.list.forEach((item=>{
        total += item.count*item.price;
        count += item.count
      }))
      for (let index = 0; index < res.list.length; index++) {
        res.list[index].priceFormat = utils.formatPrice(res.list[index].price)
        res.list[index].thumb = utils.fileMgrUrl + res.list[index].goods.pic
      }
      this.setData({
        total,
        totalFormat: utils.formatPrice(total),
        count,
        address: res.addr,
        cart: res.list
      })
      if(res.addr){
        wx.setStorage({
          data: res.addr.id,
          key: 'addressid',
        })
      }
    })
  },
  gotoOrderGoodsList(){
    wx.setStorage({
      data: this.data.cart,
      key: 'confirm_order_goods',
    })
    wx.navigateTo({
      url: '/pages/confirmOrderGoods/index',
    })
  },
  inputExtMessage(e){
    this.setData({
      extText: e.detail
    })
  },  
  submitOrder(){
    wx.showLoading({
      title: '正在下单',
    })
    const data={
      idAddress: parseInt(wx.getStorageSync('addressid')),
      message: this.data.extText
    }
    api.post(`/user/order/save?idAddress=${data.idAddress}&message=${data.message}`).then(res=>{
      wx.showLoading({
        title: '正在准备微信支付',
      })
      const ordersign = res.orderSn
      return api.post(`/pay/wx/prepare?orderSn=${ordersign}`)
    }).then((res)=>{
      console.log(res)// succ
      wx.hideLoading()
      // 微信支付
      wx.requestPayment({
        nonceStr: res.nonceStr,
        package: res.package,
        paySign: res.paySign,
        timeStamp: res.timeStamp,
        success(){
          wx.redirectTo({
            url: '/pages/pay-result/index?r=0',
          })
        },
        fail(){
          wx.redirectTo({
            url: '/pages/pay-result/index?r=1',
          })
        }
      })
    })
  }
})